import urllib2
import json
import os
import shutil
import xml.etree.cElementTree as ET

r = urllib2.urlopen("https://agile-dev-tools.appspot.com/search?format=json").read()

jsonObject = json.loads(r)

arrayLength = len(jsonObject['results'])

testsuite = ET.Element("testsuite")
testsuite.set("tests",str(arrayLength))

for review in jsonObject['results']:
	testcase = ET.SubElement(testsuite, "testcase")
	testcase.set("classname","RietveldCodeReview")
	testcase.set("name",str(review['issue']) + " - " + review['subject'])
	if not(review['closed']):
		failure = ET.SubElement(testcase, "failure")
		failure.set("type","NotClosed")
		failure.text = "This Codereview is not closed yet"

if not os.path.exists("target"):
    os.makedirs("target")
if os.path.exists("target/rietveld"):
	shutil.rmtree('target/rietveld')
os.makedirs("target/rietveld")
tree = ET.ElementTree(testsuite)
tree.write("target/rietveld/rietveld_results.xml")